package com.thoughtworks.yuyijq.generate.action;

import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.EditorAction;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.thoughtworks.yuyijq.generate.GenerateEqualsAndHashCodeHandler;

/**
 * User: yuyijq
 * Date: Oct 8, 2010
 * Time: 11:55:25 PM
 */
public class GenerateEqualsAndHashCodeAction extends EditorAction {

    public GenerateEqualsAndHashCodeAction() {
        super(new GenerateEqualsAndHashCodeHandler());
    }

    protected GenerateEqualsAndHashCodeAction(EditorActionHandler defaultHandler) {
        super(defaultHandler);
    }

    @Override
    public void update(Editor editor, Presentation presentation, DataContext dataContext) {
        Boolean enable = false;
        Project project = editor.getProject();
        PsiManager manager = PsiManager.getInstance(project);
        Editor textEditor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(textEditor.getDocument());
        PsiFile file = manager.findFile(virtualFile);
        if (file instanceof PsiJavaFile) {
            PsiJavaFile javaFile = (PsiJavaFile) file;
            if (javaFile != null) {
                PsiElement element = javaFile.getClasses()[0];
                if (element != null) {
                    PsiClass psiClass = (PsiClass) element;
                    if (psiClass != null && !psiClass.isInterface()) {
                        enable = true;
                    }
                }
            }
        }

        presentation.setEnabled(enable);
    }
}
